"use client"

import { useState, useEffect, useCallback } from "react"
import {
  Table,
  Card,
  Button,
  Input,
  Space,
  Tag,
  Modal,
  Form,
  Select,
  DatePicker,
  Row,
  Col,
  message,
  Popconfirm,
  Avatar,
  Typography,
  Drawer,
  Descriptions,
  Divider,
  Tabs,
  Progress,
} from "antd"
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  UserOutlined,
  PhoneOutlined,
  MailOutlined,
  IdcardOutlined,
} from "@ant-design/icons"
// 移除直接axios导入，改为导入api函数
import { getStaff, addStaff, updateStaff, deleteStaff } from "@/utils/api/staff"
import dayjs from "dayjs"

const { Title } = Typography
const { Option } = Select
const { TabPane } = Tabs

const StaffManagement = () => {
  const [loading, setLoading] = useState(false)
  const [staff, setStaff] = useState([])
  const [staffModalVisible, setStaffModalVisible] = useState(false)
  const [staffDetailsVisible, setStaffDetailsVisible] = useState(false)
  const [modalTitle, setModalTitle] = useState("添加员工")
  const [selectedStaff, setSelectedStaff] = useState(null)
  const [searchText, setSearchText] = useState("")
  const [form] = Form.useForm()

  // 获取员工列表 - 使用api函数
  const fetchStaff = useCallback(async () => {
    try {
      setLoading(true)
      // 直接使用getStaff()函数
      const data = await getStaff()
      setStaff(data)
    } catch (error) {
      console.error("获取员工列表错误:", error)
      message.error("获取员工列表失败")
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchStaff()
  }, [fetchStaff])

  // 搜索过滤
  const filteredStaff = staff.filter(
    (s) =>
      s.name.toLowerCase().includes(searchText.toLowerCase()) ||
      s.position.toLowerCase().includes(searchText.toLowerCase()) ||
      s.phone.includes(searchText)
  )

  // 添加或更新员工 - 使用api函数
  const handleSaveStaff = async () => {
    try {
      const values = await form.validateFields()

      if (selectedStaff) {
        // 更新员工
        await updateStaff(selectedStaff.id, values)
        message.success("员工信息更新成功")
      } else {
        // 添加员工
        await addStaff(values)
        message.success("员工添加成功")
      }

      setStaffModalVisible(false)
      form.resetFields()
      fetchStaff()
    } catch (error) {
      console.error("保存员工信息错误:", error)
      message.error("操作失败，请稍后重试")
    }
  }

  // 删除员工 - 使用api函数
  const handleDeleteStaff = async (id) => {
    try {
      await deleteStaff(id)
      message.success("员工删除成功")
      fetchStaff()
    } catch (error) {
      console.error("删除员工错误:", error)
      message.error("删除失败，请稍后重试")
    }
  }

  // 打开编辑模态框
  const handleEditStaff = (staff) => {
    setSelectedStaff(staff)
    setModalTitle("编辑员工信息")
    form.setFieldsValue({
      ...staff,
      joinDate: staff.joinDate ? dayjs(staff.joinDate) : null,
      birthday: staff.birthday ? dayjs(staff.birthday) : null,
    })
    setStaffModalVisible(true)
  }

  // 打开添加模态框
  const handleAddStaff = () => {
    setSelectedStaff(null)
    setModalTitle("添加员工")
    form.resetFields()
    setStaffModalVisible(true)
  }

  // 查看员工详情
  const handleViewStaffDetails = (staff) => {
    setSelectedStaff(staff)
    setStaffDetailsVisible(true)
  }

  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
      render: (text, record) => (
        <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
          <Avatar icon={<UserOutlined />} src={record.avatar} />
          {text}
        </div>
      ),
    },
    {
      title: "职位",
      dataIndex: "position",
      key: "position",
    },
    {
      title: "部门",
      dataIndex: "department",
      key: "department",
    },
    {
      title: "手机号码",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "入职日期",
      dataIndex: "joinDate",
      key: "joinDate",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        let color = "default"
        let text = "未知"

        switch (status) {
          case "active":
            color = "green"
            text = "在职"
            break
          case "leave":
            color = "orange"
            text = "休假"
            break
          case "resigned":
            color = "red"
            text = "离职"
            break
          default:
            color = "default"
            text = status
        }

        return <Tag color={color}>{text}</Tag>
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => handleViewStaffDetails(record)}
          />
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEditStaff(record)}
          />
          <Popconfirm
            title="确定要删除此员工吗?"
            description="此操作不可撤销!"
            onConfirm={() => handleDeleteStaff(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div className="staff-management">
      <div className="page-header">
        <Title level={4} className="page-title">
          员工管理
        </Title>
      </div>

      <Card>
        <div className="table-operations">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAddStaff}
          >
            添加员工
          </Button>
          <div className="table-search">
            <Input
              placeholder="搜索员工姓名、职位或手机号"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 300 }}
              allowClear
            />
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={filteredStaff}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 添加/编辑员工模态框 */}
      <Modal
        title={modalTitle}
        open={staffModalVisible}
        onCancel={() => setStaffModalVisible(false)}
        onOk={handleSaveStaff}
        width={720}
        okText="保存"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: "请输入姓名" }]}
              >
                <Input prefix={<UserOutlined />} placeholder="请输入姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号码"
                rules={[
                  { required: true, message: "请输入手机号码" },
                  { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号码" },
                ]}
              >
                <Input
                  prefix={<PhoneOutlined />}
                  placeholder="请输入手机号码"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="email"
                label="电子邮箱"
                rules={[
                  { required: true, message: "请输入电子邮箱" },
                  { type: "email", message: "请输入有效的电子邮箱" },
                ]}
              >
                <Input prefix={<MailOutlined />} placeholder="请输入电子邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="idNumber"
                label="身份证号"
                rules={[
                  { required: true, message: "请输入身份证号" },
                  {
                    pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                    message: "请输入有效的身份证号",
                  },
                ]}
              >
                <Input
                  prefix={<IdcardOutlined />}
                  placeholder="请输入身份证号"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="position"
                label="职位"
                rules={[{ required: true, message: "请选择职位" }]}
              >
                <Select placeholder="请选择职位">
                  <Option value="manager">婚礼策划经理</Option>
                  <Option value="planner">婚礼策划师</Option>
                  <Option value="coordinator">婚礼协调员</Option>
                  <Option value="designer">婚礼设计师</Option>
                  <Option value="photographer">婚礼摄影师</Option>
                  <Option value="assistant">婚礼助理</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="department"
                label="部门"
                rules={[{ required: true, message: "请选择部门" }]}
              >
                <Select placeholder="请选择部门">
                  <Option value="planning">策划部</Option>
                  <Option value="design">设计部</Option>
                  <Option value="photography">摄影部</Option>
                  <Option value="coordination">协调部</Option>
                  <Option value="finance">财务部</Option>
                  <Option value="admin">行政部</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="joinDate"
                label="入职日期"
                rules={[{ required: true, message: "请选择入职日期" }]}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  placeholder="请选择入职日期"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="birthday" label="出生日期">
                <DatePicker
                  style={{ width: "100%" }}
                  placeholder="请选择出生日期"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: "请选择状态" }]}
              >
                <Select placeholder="请选择状态">
                  <Option value="active">在职</Option>
                  <Option value="leave">休假</Option>
                  <Option value="resigned">离职</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="salary"
                label="薪资(元/月)"
                rules={[{ required: true, message: "请输入薪资" }]}
              >
                <Input type="number" placeholder="请输入薪资" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="address" label="住址">
            <Input.TextArea rows={2} placeholder="请输入住址" />
          </Form.Item>

          <Form.Item name="notes" label="备注">
            <Input.TextArea rows={2} placeholder="请输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 员工详情抽屉 */}
      <Drawer
        title="员工详情"
        width={720}
        placement="right"
        onClose={() => setStaffDetailsVisible(false)}
        open={staffDetailsVisible}
        extra={
          <Space>
            <Button
              onClick={() => {
                setStaffDetailsVisible(false)
                handleEditStaff(selectedStaff)
              }}
            >
              编辑
            </Button>
          </Space>
        }
      >
        {selectedStaff && (
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本信息" key="1">
              <div style={{ textAlign: "center", marginBottom: 20 }}>
                <Avatar
                  size={64}
                  icon={<UserOutlined />}
                  src={selectedStaff.avatar}
                />
                <Title level={5} style={{ marginTop: 10, marginBottom: 0 }}>
                  {selectedStaff.name}
                </Title>
                <div>{selectedStaff.position}</div>
              </div>

              <Descriptions bordered column={2}>
                <Descriptions.Item label="姓名">
                  {selectedStaff.name}
                </Descriptions.Item>
                <Descriptions.Item label="职位">
                  {selectedStaff.position}
                </Descriptions.Item>
                <Descriptions.Item label="部门">
                  {selectedStaff.department}
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  {(() => {
                    switch (selectedStaff.status) {
                      case "active":
                        return <Tag color="green">在职</Tag>
                      case "leave":
                        return <Tag color="orange">休假</Tag>
                      case "resigned":
                        return <Tag color="red">离职</Tag>
                      default:
                        return <Tag>{selectedStaff.status}</Tag>
                    }
                  })()}
                </Descriptions.Item>
                <Descriptions.Item label="手机号码">
                  {selectedStaff.phone}
                </Descriptions.Item>
                <Descriptions.Item label="电子邮箱">
                  {selectedStaff.email}
                </Descriptions.Item>
                <Descriptions.Item label="入职日期">
                  {selectedStaff.joinDate}
                </Descriptions.Item>
                <Descriptions.Item label="出生日期">
                  {selectedStaff.birthday}
                </Descriptions.Item>
                <Descriptions.Item label="身份证号" span={2}>
                  {selectedStaff.idNumber}
                </Descriptions.Item>
                <Descriptions.Item label="住址" span={2}>
                  {selectedStaff.address}
                </Descriptions.Item>
                <Descriptions.Item label="备注" span={2}>
                  {selectedStaff.notes}
                </Descriptions.Item>
              </Descriptions>
            </TabPane>

            <TabPane tab="工作统计" key="2">
              <Card title="工作表现">
                <div style={{ marginBottom: 20 }}>
                  <div style={{ marginBottom: 8 }}>客户满意度</div>
                  <Progress
                    percent={92}
                    status="active"
                    strokeColor="#52c41a"
                  />
                </div>
                <div style={{ marginBottom: 20 }}>
                  <div style={{ marginBottom: 8 }}>项目完成率</div>
                  <Progress
                    percent={88}
                    status="active"
                    strokeColor="#1890ff"
                  />
                </div>
                <div style={{ marginBottom: 20 }}>
                  <div style={{ marginBottom: 8 }}>团队协作</div>
                  <Progress
                    percent={95}
                    status="active"
                    strokeColor="#C13584"
                  />
                </div>
                <div>
                  <div style={{ marginBottom: 8 }}>创新能力</div>
                  <Progress
                    percent={85}
                    status="active"
                    strokeColor="#722ed1"
                  />
                </div>
              </Card>

              <Card title="项目参与情况" style={{ marginTop: 16 }}>
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    marginBottom: 16,
                  }}
                >
                  <div>
                    <div
                      style={{
                        fontSize: 24,
                        fontWeight: "bold",
                        color: "#1890ff",
                      }}
                    >
                      15
                    </div>
                    <div>进行中项目</div>
                  </div>
                  <div>
                    <div
                      style={{
                        fontSize: 24,
                        fontWeight: "bold",
                        color: "#52c41a",
                      }}
                    >
                      42
                    </div>
                    <div>已完成项目</div>
                  </div>
                  <div>
                    <div
                      style={{
                        fontSize: 24,
                        fontWeight: "bold",
                        color: "#faad14",
                      }}
                    >
                      3
                    </div>
                    <div>待确认项目</div>
                  </div>
                </div>

                <div>
                  <div style={{ marginBottom: 8 }}>本月工作量</div>
                  <Progress
                    percent={78}
                    status="active"
                    strokeColor="#C13584"
                  />
                </div>
              </Card>
            </TabPane>

            <TabPane tab="薪资信息" key="3">
              <Card>
                <div style={{ textAlign: "center", marginBottom: 20 }}>
                  <div style={{ fontSize: 16, color: "#666" }}>当前薪资</div>
                  <div
                    style={{
                      fontSize: 28,
                      fontWeight: "bold",
                      color: "#C13584",
                    }}
                  >
                    {selectedStaff.salary} 元/月
                  </div>
                </div>

                <Divider>薪资构成</Divider>

                <div style={{ marginBottom: 20 }}>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      marginBottom: 8,
                    }}
                  >
                    <span>基本工资</span>
                    <span>{Math.round(selectedStaff.salary * 0.6)} 元</span>
                  </div>
                  <Progress
                    percent={60}
                    showInfo={false}
                    strokeColor="#1890ff"
                  />
                </div>

                <div style={{ marginBottom: 20 }}>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      marginBottom: 8,
                    }}
                  >
                    <span>绩效工资</span>
                    <span>{Math.round(selectedStaff.salary * 0.25)} 元</span>
                  </div>
                  <Progress
                    percent={25}
                    showInfo={false}
                    strokeColor="#52c41a"
                  />
                </div>

                <div style={{ marginBottom: 20 }}>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      marginBottom: 8,
                    }}
                  >
                    <span>补贴</span>
                    <span>{Math.round(selectedStaff.salary * 0.1)} 元</span>
                  </div>
                  <Progress
                    percent={10}
                    showInfo={false}
                    strokeColor="#faad14"
                  />
                </div>

                <div>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      marginBottom: 8,
                    }}
                  >
                    <span>奖金</span>
                    <span>{Math.round(selectedStaff.salary * 0.05)} 元</span>
                  </div>
                  <Progress
                    percent={5}
                    showInfo={false}
                    strokeColor="#C13584"
                  />
                </div>
              </Card>
            </TabPane>
          </Tabs>
        )}
      </Drawer>
    </div>
  )
}

export default StaffManagement
